package main

import (
	"context"
	"encoding/json"
	"fmt"
	"html/template"
	"net/http"
	"os"
	"os/signal"
	"sync"
	"syscall"
	"time"

	"github.com/gorilla/mux"
	"github.com/gorilla/websocket"

	"sokit-go/network"
	"sokit-go/utils"
)

// ClientInfo 存储客户端连接信息
type ClientInfo struct {
	conn  *websocket.Conn
	mutex sync.Mutex
}

// WebApp Web应用程序结构
type WebApp struct {
	manager      *network.NetworkManager
	upgrader     websocket.Upgrader
	clients      map[*websocket.Conn]*ClientInfo
	broadcast    chan []byte
	clientsMutex sync.RWMutex
	// 频率限制相关字段
	lastDataBroadcast  time.Time
	dataBroadcastMutex sync.Mutex
	// 工具组件
	dataFormat *utils.DataFormat
	statistics *utils.Statistics
	// 日志管理器
	logger *utils.Logger
	// 数据库管理器
	database *utils.Database
}

// Config 配置数据模型（已废弃，使用新的配置管理器）
// type Config struct {
// 	ID       uint   `gorm:"primaryKey"`
// 	Section  string `gorm:"index"`
// 	Key      string `gorm:"index"`
// 	Value    string
// 	CreateAt time.Time
// 	UpdateAt time.Time
// }

// WebSocketMessage WebSocket消息结构
type WebSocketMessage struct {
	Type string      `json:"type"`
	Data interface{} `json:"data"`
}

// NewWebApp 创建新的Web应用程序
func NewWebApp() *WebApp {
	app := &WebApp{
		manager:   network.NewNetworkManager(),
		upgrader:  websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }},
		clients:   make(map[*websocket.Conn]*ClientInfo),
		broadcast: make(chan []byte, 1024),
	}

	// 初始化组件
	app.initComponents()

	// 设置网络管理器回调
	app.setupManagerCallbacks()

	return app
}

// initComponents 初始化组件
func (app *WebApp) initComponents() {
	// 初始化日志管理器
	app.logger = utils.GetLogger()
	app.logger.Info("应用程序启动")

	// 初始化数据库管理器
	app.database = utils.GetDatabase()

	// 初始化其他组件
	app.dataFormat = utils.GetDataFormatInstance()
	app.statistics = utils.NewStatistics()

	app.logger.Info("组件初始化完成")
}

// setupManagerCallbacks 设置网络管理器回调
func (app *WebApp) setupManagerCallbacks() {
	// 客户端事件回调
	app.manager.OnClientEvent = func(instance *network.ClientInstance, event string, data interface{}) {
		app.broadcastMessage("client_event", map[string]interface{}{
			"instance_id":   instance.ID,
			"instance_name": instance.Name,
			"event":         event,
			"data":          data,
			"time":          time.Now().Format("2006-01-02 15:04:05"),
		})

		// 兼容旧的消息格式
		switch event {
		case "connected":
			app.broadcastMessage("client_connected", map[string]interface{}{
				"instance_id": instance.ID,
				"status":      "connected",
				"time":        time.Now().Format("2006-01-02 15:04:05"),
			})
		case "disconnected":
			app.broadcastMessage("client_disconnected", map[string]interface{}{
				"instance_id": instance.ID,
				"status":      "disconnected",
				"time":        time.Now().Format("2006-01-02 15:04:05"),
			})
		case "data_received":
			app.broadcastDataMessage("client_data_received", map[string]interface{}{
				"instance_id": instance.ID,
				"data":        data,
				"time":        time.Now().Format("2006-01-02 15:04:05"),
			})
		case "error":
			app.broadcastMessage("client_error", map[string]interface{}{
				"instance_id": instance.ID,
				"error":       data,
				"time":        time.Now().Format("2006-01-02 15:04:05"),
			})
		}
	}

	// 服务器事件回调
	app.manager.OnServerEvent = func(instance *network.ServerInstance, event string, data interface{}) {
		app.broadcastMessage("server_event", map[string]interface{}{
			"instance_id":   instance.ID,
			"instance_name": instance.Name,
			"event":         event,
			"data":          data,
			"time":          time.Now().Format("2006-01-02 15:04:05"),
		})

		// 兼容旧的消息格式
		switch event {
		case "started":
			app.broadcastMessage("server_started", map[string]interface{}{
				"instance_id": instance.ID,
				"status":      "started",
				"time":        time.Now().Format("2006-01-02 15:04:05"),
			})
		case "stopped":
			app.broadcastMessage("server_stopped", map[string]interface{}{
				"instance_id": instance.ID,
				"status":      "stopped",
				"time":        time.Now().Format("2006-01-02 15:04:05"),
			})
		case "client_connected":
			app.broadcastMessage("server_client_connected", map[string]interface{}{
				"instance_id": instance.ID,
				"address":     data,
				"time":        time.Now().Format("2006-01-02 15:04:05"),
			})
		case "client_disconnected":
			app.broadcastMessage("server_client_disconnected", map[string]interface{}{
				"instance_id": instance.ID,
				"address":     data,
				"time":        time.Now().Format("2006-01-02 15:04:05"),
			})
		case "data_received":
			if dataMap, ok := data.(map[string]interface{}); ok {
				app.broadcastDataMessage("server_data_received", map[string]interface{}{
					"instance_id": instance.ID,
					"address":     dataMap["address"],
					"data":        dataMap["data"],
					"time":        time.Now().Format("2006-01-02 15:04:05"),
				})
			}
		case "error":
			app.broadcastMessage("server_error", map[string]interface{}{
				"instance_id": instance.ID,
				"error":       data,
				"time":        time.Now().Format("2006-01-02 15:04:05"),
			})
		}
	}

	// 转发事件回调
	app.manager.OnTransferEvent = func(instance *network.TransferInstance, event string, data interface{}) {
		app.broadcastMessage("transfer_event", map[string]interface{}{
			"instance_id":   instance.ID,
			"instance_name": instance.Name,
			"event":         event,
			"data":          data,
			"time":          time.Now().Format("2006-01-02 15:04:05"),
		})

		// 兼容旧的消息格式
		switch event {
		case "started":
			app.broadcastMessage("transfer_started", map[string]interface{}{
				"instance_id": instance.ID,
				"status":      "started",
				"time":        time.Now().Format("2006-01-02 15:04:05"),
			})
		case "stopped":
			app.broadcastMessage("transfer_stopped", map[string]interface{}{
				"instance_id": instance.ID,
				"status":      "stopped",
				"time":        time.Now().Format("2006-01-02 15:04:05"),
			})
		case "error":
			app.broadcastMessage("transfer_error", map[string]interface{}{
				"instance_id": instance.ID,
				"error":       data,
				"time":        time.Now().Format("2006-01-02 15:04:05"),
			})
		}
	}
}

// broadcastDataMessage 带频率限制的数据广播（最多每秒1次）
func (app *WebApp) broadcastDataMessage(msgType string, data interface{}) {
	app.dataBroadcastMutex.Lock()
	defer app.dataBroadcastMutex.Unlock()

	now := time.Now()
	if now.Sub(app.lastDataBroadcast) < time.Second {
		return // 频率限制，跳过此次广播
	}

	app.lastDataBroadcast = now
	app.broadcastMessage(msgType, data)
}

// broadcastMessage 广播消息到所有WebSocket客户端
func (app *WebApp) broadcastMessage(msgType string, data interface{}) {
	message := WebSocketMessage{
		Type: msgType,
		Data: data,
	}

	jsonData, err := json.Marshal(message)
	if err != nil {
		app.logger.Error("消息序列化失败: %v", err)
		return
	}

	select {
	case app.broadcast <- jsonData:
	default:
		// 如果广播通道满了，记录日志但不阻塞
		app.logger.Warn("广播通道已满，消息被丢弃")
	}
}

// handleWebSocket 处理WebSocket连接
func (app *WebApp) handleWebSocket(w http.ResponseWriter, r *http.Request) {
	conn, err := app.upgrader.Upgrade(w, r, nil)
	if err != nil {
		app.logger.Error("WebSocket升级失败: %v", err)
		return
	}
	defer conn.Close()

	// 创建客户端信息
	clientInfo := &ClientInfo{
		conn: conn,
	}

	app.clientsMutex.Lock()
	app.clients[conn] = clientInfo
	app.clientsMutex.Unlock()

	app.logger.Info("新的WebSocket客户端连接，总连接数: %d", len(app.clients))

	for {
		var msg WebSocketMessage
		err := conn.ReadJSON(&msg)
		if err != nil {
			// 检查是否是WebSocket正常关闭错误
			if websocket.IsCloseError(err, websocket.CloseGoingAway, websocket.CloseNormalClosure, websocket.CloseNoStatusReceived) {
				app.logger.Info("WebSocket客户端正常断开连接")
			} else {
				app.logger.Error("WebSocket读取错误: %v", err)
			}
			app.clientsMutex.Lock()
			delete(app.clients, conn)
			app.clientsMutex.Unlock()
			break
		}

		app.handleWebSocketMessage(conn, &msg)
	}
}

// safeWriteJSON 安全地向WebSocket写入JSON数据
func (app *WebApp) safeWriteJSON(conn *websocket.Conn, msg WebSocketMessage) error {
	app.clientsMutex.RLock()
	clientInfo, exists := app.clients[conn]
	app.clientsMutex.RUnlock()

	if !exists {
		return nil // 连接已关闭
	}

	clientInfo.mutex.Lock()
	defer clientInfo.mutex.Unlock()

	return conn.WriteJSON(msg)
}

// handleWebSocketMessage 处理WebSocket消息
func (app *WebApp) handleWebSocketMessage(conn *websocket.Conn, msg *WebSocketMessage) {
	switch msg.Type {
	// === 客户端管理 ===
	case "create_client":
		data := msg.Data.(map[string]interface{})
		instance, err := app.manager.CreateClient(
			data["name"].(string),
			data["host"].(string),
			data["port"].(string),
			data["protocol"].(string),
		)
		if err != nil {
			app.safeWriteJSON(conn, WebSocketMessage{Type: "error", Data: map[string]interface{}{"message": err.Error()}})
		} else {
			app.safeWriteJSON(conn, WebSocketMessage{Type: "client_created", Data: map[string]interface{}{
				"instance": instance,
			}})
		}

	case "start_client":
		data := msg.Data.(map[string]interface{})
		err := app.manager.StartClient(data["id"].(string))
		if err != nil {
			app.safeWriteJSON(conn, WebSocketMessage{Type: "error", Data: map[string]interface{}{"message": err.Error()}})
		}

	case "stop_client":
		data := msg.Data.(map[string]interface{})
		err := app.manager.StopClient(data["id"].(string))
		if err != nil {
			app.safeWriteJSON(conn, WebSocketMessage{Type: "error", Data: map[string]interface{}{"message": err.Error()}})
		}

	case "delete_client":
		data := msg.Data.(map[string]interface{})
		err := app.manager.DeleteClient(data["id"].(string))
		if err != nil {
			app.safeWriteJSON(conn, WebSocketMessage{Type: "error", Data: map[string]interface{}{"message": err.Error()}})
		}

	case "send_to_client":
		data := msg.Data.(map[string]interface{})
		err := app.manager.SendToClient(data["id"].(string), data["message"].(string))
		if err != nil {
			app.safeWriteJSON(conn, WebSocketMessage{Type: "error", Data: map[string]interface{}{"message": err.Error()}})
		}

	case "list_clients":
		clients := app.manager.ListClients()
		app.safeWriteJSON(conn, WebSocketMessage{Type: "clients_list", Data: map[string]interface{}{
			"clients": clients,
		}})

	// === 兼容旧的单实例API ===
	case "client_connect":
		data := msg.Data.(map[string]interface{})
		// 查找第一个客户端实例或创建新的
		clients := app.manager.ListClients()
		var clientID string
		if len(clients) > 0 {
			clientID = clients[0].ID
		} else {
			instance, err := app.manager.CreateClient("默认客户端",
				data["host"].(string), data["port"].(string), data["protocol"].(string))
			if err != nil {
				app.safeWriteJSON(conn, WebSocketMessage{Type: "error", Data: map[string]interface{}{"message": err.Error()}})
				return
			}
			clientID = instance.ID
		}
		err := app.manager.StartClient(clientID)
		if err != nil {
			app.safeWriteJSON(conn, WebSocketMessage{Type: "error", Data: map[string]interface{}{"message": err.Error()}})
		}

	case "client_disconnect":
		clients := app.manager.ListClients()
		if len(clients) > 0 {
			app.manager.StopClient(clients[0].ID)
		}

	case "client_send":
		data := msg.Data.(map[string]interface{})
		clients := app.manager.ListClients()
		if len(clients) > 0 {
			err := app.manager.SendToClient(clients[0].ID, data["message"].(string))
			if err != nil {
				app.safeWriteJSON(conn, WebSocketMessage{Type: "error", Data: map[string]interface{}{"message": err.Error()}})
			}
		} else {
			app.safeWriteJSON(conn, WebSocketMessage{Type: "error", Data: map[string]interface{}{"message": "没有可用的客户端实例"}})
		}

	// === 服务器管理 ===
	case "create_server":
		data := msg.Data.(map[string]interface{})
		instance, err := app.manager.CreateServer(
			data["name"].(string),
			data["port"].(string),
			data["protocol"].(string),
		)
		if err != nil {
			app.safeWriteJSON(conn, WebSocketMessage{Type: "error", Data: map[string]interface{}{"message": err.Error()}})
		} else {
			app.safeWriteJSON(conn, WebSocketMessage{Type: "server_created", Data: map[string]interface{}{
				"instance": instance,
			}})
		}

	case "start_server":
		data := msg.Data.(map[string]interface{})
		err := app.manager.StartServer(data["id"].(string))
		if err != nil {
			app.safeWriteJSON(conn, WebSocketMessage{Type: "error", Data: map[string]interface{}{"message": err.Error()}})
		}

	case "stop_server":
		data := msg.Data.(map[string]interface{})
		err := app.manager.StopServer(data["id"].(string))
		if err != nil {
			app.safeWriteJSON(conn, WebSocketMessage{Type: "error", Data: map[string]interface{}{"message": err.Error()}})
		}

	case "delete_server":
		data := msg.Data.(map[string]interface{})
		err := app.manager.DeleteServer(data["id"].(string))
		if err != nil {
			app.safeWriteJSON(conn, WebSocketMessage{Type: "error", Data: map[string]interface{}{"message": err.Error()}})
		}

	case "send_to_server":
		data := msg.Data.(map[string]interface{})
		err := app.manager.SendToServer(data["id"].(string), data["message"].(string))
		if err != nil {
			app.safeWriteJSON(conn, WebSocketMessage{Type: "error", Data: map[string]interface{}{"message": err.Error()}})
		}

	case "list_servers":
		servers := app.manager.ListServers()
		app.safeWriteJSON(conn, WebSocketMessage{Type: "servers_list", Data: map[string]interface{}{
			"servers": servers,
		}})

	// === 兼容旧的单实例API ===
	case "server_start":
		data := msg.Data.(map[string]interface{})
		port := data["port"].(string)
		protocol := data["protocol"].(string)

		app.logger.Info("收到服务器启动请求，端口: %s, 协议: %s", port, protocol)

		// 查找第一个服务器实例或创建新的
		servers := app.manager.ListServers()
		var serverID string
		if len(servers) > 0 {
			serverID = servers[0].ID
		} else {
			instance, err := app.manager.CreateServer("默认服务器", port, protocol)
			if err != nil {
				app.safeWriteJSON(conn, WebSocketMessage{Type: "error", Data: map[string]interface{}{"message": err.Error()}})
				return
			}
			serverID = instance.ID
		}
		err := app.manager.StartServer(serverID)
		if err != nil {
			app.safeWriteJSON(conn, WebSocketMessage{Type: "error", Data: map[string]interface{}{"message": err.Error()}})
		}

	case "server_stop":
		servers := app.manager.ListServers()
		if len(servers) > 0 {
			app.manager.StopServer(servers[0].ID)
		}

	case "server_send":
		data := msg.Data.(map[string]interface{})
		servers := app.manager.ListServers()
		if len(servers) > 0 {
			err := app.manager.SendToServer(servers[0].ID, data["message"].(string))
			if err != nil {
				app.safeWriteJSON(conn, WebSocketMessage{Type: "error", Data: map[string]interface{}{"message": err.Error()}})
			}
		} else {
			app.safeWriteJSON(conn, WebSocketMessage{Type: "error", Data: map[string]interface{}{"message": "没有可用的服务器实例"}})
		}

	// === 转发管理 ===
	case "transfer_list":
		transfers := app.manager.ListTransfers()
		app.logger.Info("发送转发列表，共 %d 个转发", len(transfers))
		app.safeWriteJSON(conn, WebSocketMessage{Type: "transfer_list", Data: map[string]interface{}{
			"transfers": transfers,
		}})

	// === 新的多实例转发管理 ===
	case "transfer_create":
		data, ok := msg.Data.(map[string]interface{})
		if !ok {
			app.safeWriteJSON(conn, WebSocketMessage{Type: "transfer_create_failed", Data: map[string]interface{}{"error": "无效的数据格式"}})
			return
		}

		// 安全的类型转换
		name, _ := data["name"].(string)
		localHost, _ := data["local_host"].(string)
		targetHost, _ := data["target_host"].(string)
		protocol, _ := data["protocol"].(string)

		if name == "" || localHost == "" || targetHost == "" || protocol == "" {
			app.safeWriteJSON(conn, WebSocketMessage{Type: "transfer_create_failed", Data: map[string]interface{}{"error": "缺少必需的参数"}})
			return
		}

		instance, err := app.manager.CreateTransfer(
			name,
			localHost,
			fmt.Sprint(data["local_port"]),
			targetHost,
			fmt.Sprint(data["target_port"]),
			protocol,
		)
		if err != nil {
			app.safeWriteJSON(conn, WebSocketMessage{Type: "transfer_create_failed", Data: map[string]interface{}{"error": err.Error()}})
		} else {
			app.safeWriteJSON(conn, WebSocketMessage{Type: "transfer_created", Data: map[string]interface{}{"name": instance.Name}})
			// 自动发送更新的转发列表
			transfers := app.manager.ListTransfers()
			app.safeWriteJSON(conn, WebSocketMessage{Type: "transfer_list", Data: map[string]interface{}{
				"transfers": transfers,
			}})
		}

	case "transfer_start":
		if msg.Data != nil {
			if data, ok := msg.Data.(map[string]interface{}); ok {
				if id, exists := data["id"]; exists {
					// 新的多实例方式
					if idStr, ok := id.(string); ok {
						err := app.manager.StartTransfer(idStr)
						if err != nil {
							app.safeWriteJSON(conn, WebSocketMessage{Type: "transfer_error", Data: map[string]interface{}{"error": err.Error()}})
						} else {
							app.safeWriteJSON(conn, WebSocketMessage{Type: "transfer_started", Data: map[string]interface{}{"name": "转发"}})
							// 自动发送更新的转发列表
							transfers := app.manager.ListTransfers()
							app.safeWriteJSON(conn, WebSocketMessage{Type: "transfer_list", Data: map[string]interface{}{
								"transfers": transfers,
							}})
						}
						return
					}
				}
			}
		}
		// 兼容旧的单实例API
		data := msg.Data.(map[string]interface{})
		// 查找第一个转发实例或创建新的
		transfers := app.manager.ListTransfers()
		var transferID string
		if len(transfers) > 0 {
			transferID = transfers[0].ID
		} else {
			instance, err := app.manager.CreateTransfer("默认转发",
				data["local_host"].(string),
				data["local_port"].(string),
				data["target_host"].(string),
				data["target_port"].(string),
				data["protocol"].(string),
			)
			if err != nil {
				app.safeWriteJSON(conn, WebSocketMessage{Type: "error", Data: map[string]interface{}{"message": err.Error()}})
				return
			}
			transferID = instance.ID
		}
		err := app.manager.StartTransfer(transferID)
		if err != nil {
			app.safeWriteJSON(conn, WebSocketMessage{Type: "error", Data: map[string]interface{}{"message": err.Error()}})
		} else {
			// 自动发送更新的转发列表
			transfers := app.manager.ListTransfers()
			app.safeWriteJSON(conn, WebSocketMessage{Type: "transfer_list", Data: map[string]interface{}{
				"transfers": transfers,
			}})
		}

	case "transfer_stop":
		if msg.Data != nil {
			if data, ok := msg.Data.(map[string]interface{}); ok {
				if id, exists := data["id"]; exists {
					// 新的多实例方式
					if idStr, ok := id.(string); ok {
						err := app.manager.StopTransfer(idStr)
						if err != nil {
							app.safeWriteJSON(conn, WebSocketMessage{Type: "transfer_error", Data: map[string]interface{}{"error": err.Error()}})
						} else {
							app.safeWriteJSON(conn, WebSocketMessage{Type: "transfer_stopped", Data: map[string]interface{}{"name": "转发"}})
							// 自动发送更新的转发列表
							transfers := app.manager.ListTransfers()
							app.safeWriteJSON(conn, WebSocketMessage{Type: "transfer_list", Data: map[string]interface{}{
								"transfers": transfers,
							}})
						}
						return
					}
				}
			}
		}
		// 兼容旧的单实例API
		transfers := app.manager.ListTransfers()
		if len(transfers) > 0 {
			app.manager.StopTransfer(transfers[0].ID)
			// 自动发送更新的转发列表
			updatedTransfers := app.manager.ListTransfers()
			app.safeWriteJSON(conn, WebSocketMessage{Type: "transfer_list", Data: map[string]interface{}{
				"transfers": updatedTransfers,
			}})
		}

	case "transfer_delete":
		data, ok := msg.Data.(map[string]interface{})
		if !ok {
			app.safeWriteJSON(conn, WebSocketMessage{Type: "transfer_error", Data: map[string]interface{}{"error": "无效的数据格式"}})
			return
		}

		idStr, ok := data["id"].(string)
		if !ok || idStr == "" {
			app.safeWriteJSON(conn, WebSocketMessage{Type: "transfer_error", Data: map[string]interface{}{"error": "无效的ID"}})
			return
		}

		err := app.manager.DeleteTransfer(idStr)
		if err != nil {
			app.safeWriteJSON(conn, WebSocketMessage{Type: "transfer_error", Data: map[string]interface{}{"error": err.Error()}})
		} else {
			app.safeWriteJSON(conn, WebSocketMessage{Type: "transfer_deleted", Data: map[string]interface{}{"id": idStr}})
			// 自动发送更新的转发列表
			transfers := app.manager.ListTransfers()
			app.safeWriteJSON(conn, WebSocketMessage{Type: "transfer_list", Data: map[string]interface{}{
				"transfers": transfers,
			}})
		}

	case "transfer_stop_all":
		transfers := app.manager.ListTransfers()
		for _, transfer := range transfers {
			if transfer.Status == network.StatusRunning {
				app.manager.StopTransfer(transfer.ID)
			}
		}
		app.safeWriteJSON(conn, WebSocketMessage{Type: "transfer_all_stopped", Data: map[string]interface{}{}})
		// 自动发送更新的转发列表
		updatedTransfers := app.manager.ListTransfers()
		app.safeWriteJSON(conn, WebSocketMessage{Type: "transfer_list", Data: map[string]interface{}{
			"transfers": updatedTransfers,
		}})

	// === 管理器统计 ===
	case "get_manager_stats":
		stats := app.manager.GetStats()
		app.safeWriteJSON(conn, WebSocketMessage{Type: "manager_stats", Data: stats})

	case "get_local_ips":
		ips := utils.GetLocalIPv4Addresses()
		app.safeWriteJSON(conn, WebSocketMessage{
			Type: "local_ips",
			Data: map[string]interface{}{
				"ips": ips,
			},
		})

	case "get_config":
		config := utils.GetConfig()
		app.safeWriteJSON(conn, WebSocketMessage{
			Type: "config",
			Data: map[string]interface{}{
				"enabled_features":   config.GetEnabledFeatures(),
				"transfer_config":    config.GetTransferConfig(),
				"server_config":      config.GetServerConfig(),
				"performance_config": config.GetPerformanceConfig(),
			},
		})
		// 同时发送转发列表
		transfers := app.manager.ListTransfers()
		app.safeWriteJSON(conn, WebSocketMessage{Type: "transfer_list", Data: map[string]interface{}{
			"transfers": transfers,
		}})

	case "convert_ascii_to_hex":
		data := msg.Data.(map[string]interface{})
		input := data["input"].(string)
		result, err := app.dataFormat.ASCII2Hex(input)
		if err != nil {
			app.safeWriteJSON(conn, WebSocketMessage{Type: "error", Data: map[string]interface{}{"message": err.Error()}})
		} else {
			app.safeWriteJSON(conn, WebSocketMessage{
				Type: "convert_result",
				Data: map[string]interface{}{
					"result": result,
					"type":   "ascii_to_hex",
				},
			})
		}

	case "convert_hex_to_ascii":
		data := msg.Data.(map[string]interface{})
		input := data["input"].(string)
		result, err := app.dataFormat.Hex2ASCII(input)
		if err != nil {
			app.safeWriteJSON(conn, WebSocketMessage{Type: "error", Data: map[string]interface{}{"message": err.Error()}})
		} else {
			app.safeWriteJSON(conn, WebSocketMessage{
				Type: "convert_result",
				Data: map[string]interface{}{
					"result": result,
					"type":   "hex_to_ascii",
				},
			})
		}

	case "get_statistics":
		stats := app.statistics.GetCurrentStats()
		totalSent, totalReceived, packetsSent, packetsReceived,
			totalConns, activeConns, maxConns, uptime := app.statistics.GetTotalStats()

		app.safeWriteJSON(conn, WebSocketMessage{
			Type: "statistics",
			Data: map[string]interface{}{
				"current": map[string]interface{}{
					"bytes_sent":     stats.BytesSent,
					"bytes_received": stats.BytesReceived,
					"send_rate":      stats.SendRate,
					"receive_rate":   stats.ReceiveRate,
					"active_conns":   stats.ActiveConns,
				},
				"total": map[string]interface{}{
					"bytes_sent":         totalSent,
					"bytes_received":     totalReceived,
					"packets_sent":       packetsSent,
					"packets_received":   packetsReceived,
					"total_connections":  totalConns,
					"active_connections": activeConns,
					"max_connections":    maxConns,
					"uptime":             uptime.Seconds(),
				},
			},
		})

	case "reset_statistics":
		app.statistics.Reset()
		app.safeWriteJSON(conn, WebSocketMessage{
			Type: "statistics_reset",
			Data: map[string]interface{}{
				"message": "统计信息已重置",
			},
		})

	case "set_config":
		data := msg.Data.(map[string]interface{})
		app.setConfig(data["section"].(string), data["key"].(string), data["value"].(string))
	}
}

// getConfig 获取配置（已废弃，使用新的配置管理器）
func (app *WebApp) getConfig(section, key, defaultValue string) string {
	app.logger.Warn("使用了废弃的getConfig函数")
	return defaultValue
}

// setConfig 设置配置（已废弃，使用新的配置管理器）
func (app *WebApp) setConfig(section, key, value string) {
	app.logger.Warn("使用了废弃的setConfig函数")
}

// indexHandler 处理首页
func (app *WebApp) indexHandler(w http.ResponseWriter, r *http.Request) {
	tmpl := template.Must(template.ParseFiles("web/templates/index.html"))
	tmpl.Execute(w, nil)
}

// setupRoutes 设置路由
func (app *WebApp) setupRoutes() *mux.Router {
	r := mux.NewRouter()

	// 静态文件
	r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("web/static/"))))

	// WebSocket
	r.HandleFunc("/ws", app.handleWebSocket)

	// 首页
	r.HandleFunc("/", app.indexHandler)

	return r
}

// handleBroadcast 处理广播消息
func (app *WebApp) handleBroadcast() {
	for {
		message := <-app.broadcast
		app.clientsMutex.RLock()
		for conn, clientInfo := range app.clients {
			go func(conn *websocket.Conn, clientInfo *ClientInfo, message []byte) {
				clientInfo.mutex.Lock()
				defer clientInfo.mutex.Unlock()

				err := conn.WriteMessage(websocket.TextMessage, message)
				if err != nil {
					app.logger.Error("WebSocket写入失败: %v", err)
					conn.Close()
					app.clientsMutex.Lock()
					delete(app.clients, conn)
					app.clientsMutex.Unlock()
				}
			}(conn, clientInfo, message)
		}
		app.clientsMutex.RUnlock()
	}
}

// run 运行Web服务器
func (app *WebApp) run() {
	go app.handleBroadcast()
	r := app.setupRoutes()

	config := utils.GetConfig()
	serverConfig := config.GetServerConfig()
	port := fmt.Sprintf(":%d", serverConfig.DefaultPort)

	server := &http.Server{
		Addr:    port,
		Handler: r,
	}

	// 启动服务器
	go func() {
		app.logger.Info("Web服务器启动在 http://localhost%s", port)
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			app.logger.Error("Web服务器启动失败: %v", err)
		}
	}()

	// 等待中断信号
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

	<-sigChan
	app.logger.Info("收到关闭信号，正在优雅关闭...")

	// 优雅关闭
	app.shutdown(server)
}

// shutdown 优雅关闭应用程序
func (app *WebApp) shutdown(server *http.Server) {
	// 创建超时上下文
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	// 关闭HTTP服务器
	if err := server.Shutdown(ctx); err != nil {
		app.logger.Error("服务器关闭失败: %v", err)
	}

	// 停止所有转发
	transfers := app.manager.ListTransfers()
	for _, transfer := range transfers {
		if transfer.Status == network.StatusRunning {
			app.logger.Info("停止转发: %s", transfer.Name)
			app.manager.StopTransfer(transfer.ID)
		}
	}

	// 停止所有服务器
	servers := app.manager.ListServers()
	for _, server := range servers {
		if server.Status == network.StatusRunning {
			app.logger.Info("停止服务器: %s", server.Name)
			app.manager.StopServer(server.ID)
		}
	}

	// 停止所有客户端
	clients := app.manager.ListClients()
	for _, client := range clients {
		if client.Status == network.StatusRunning {
			app.logger.Info("停止客户端: %s", client.Name)
			app.manager.StopClient(client.ID)
		}
	}

	// 关闭数据库连接
	if err := app.database.Close(); err != nil {
		app.logger.Error("数据库关闭失败: %v", err)
	}

	// 关闭日志文件
	app.logger.Close()

	app.logger.Info("应用程序已优雅关闭")
}

func main() {
	app := NewWebApp()
	app.run()
}
